package net.web.milkteapos.module;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.web.milkteapos.bean.Employee;
import net.web.milkteapos.bean.Money;
import net.web.milkteapos.bean.Product;
import net.web.milkteapos.bean.Sale;
import net.web.milkteapos.bean.SaleList;
import net.web.milkteapos.bean.SalesLineItem;



import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

@IocBean
@At("/sale")
@Ok("json")
@Fail("http:500")
public class SaleModule {

	@Inject
	protected Dao dao;
	//private int number;
	//private int orderId;
	private Sale sale = new Sale();
	private boolean isComplete =false;
	
	
	/**
	 * 完成Sale
	 * @param isComplete
	 */
	public void becomeComplete(){
		isComplete =true;
	}
	
	/**
	 * @param isComplete
	 * @return
	 */
	public boolean isComplete(){
		return isComplete;
	}
	
	/**
	 * 开新的一单
	 * @return
	 */
	@At("/new_sale")
	public Object newSale() {
		sale = new Sale();
		//orderId=GenerateOrderNumber();
		return new NutMap().setv("ok", true);
	}
	
	/**
	 * 完成下单（结算）
	 * @return
	 */
	@At("/finish_sale")
	public Object finishSale() {
		Employee employee = dao.query(Employee.class, null).get(0);
		
		sale.setEmployeeId(employee.getId());
		sale.setEmployee(employee);
		sale.setOrderDate(new Date());
		Sale s = dao.insertWith(sale, "totalAmount");
		sale.setOrderId(s.getOrderId());
//		sale = dao.insertRelation(sale, "products");
		return updateList();
	}
	
	public Object updateList(){
		List<SalesLineItem> lineItems = new ArrayList<>();
		for (Product product : sale.getProducts()) {
			boolean used = false;
			if(lineItems.size() > 0) {
				for (SalesLineItem item : lineItems) {
					if(item.getProduct().getProductId() == product.getProductId()) {
						item.addQuantity();
						used = true;
						break;
					}
				}
			}
			if(!used)
				lineItems.add(new SalesLineItem(product));
		}
		NutMap re = new NutMap();
        re.setv("ok", true).setv("list", lineItems);
        re.setv("ok", true).setv("totalAmount", getTotal());
        re.setv("ok", true).setv("orderId", sale.getOrderId());
        re.setv("ok", true).setv("sum", sale.getProductSum());
        if(sale.getEmployee() != null) {
            re.setv("ok", true).setv("employee", sale.getEmployee());
        }
        if(sale.getOrderDate() != null) {
        	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            re.setv("ok", true).setv("createTime", format.format(sale.getOrderDate()));
        }
		return re;
	}
	
	/**
	 * 支付
	 * @param customerPay 客户付款金额
	 * @return
	 */
	@At("/pay")
	public Object pay(int customerPay) {
			
		NutMap re = new NutMap();
		if(customerPay>=getTotal().getAmount())
			{
			Employee employee = dao.query(Employee.class, null).get(0);
			
			sale.setEmployeeId(employee.getId());
			sale.setEmployee(employee);
			sale.setOrderDate(new Date());
//			Sale s = dao.insertWith(sale, "totalAmount");
//			sale.setOrderId(s.getOrderId());
			sale = dao.insertRelation(sale, "products");
				sale.setCustomerPay(new Money(customerPay));
				sale.setPay(true);
				dao.insertLinks(sale, "customerPay");
				System.out.println("查错标记");
				dao.update(sale);
				re.setv("ok", true).setv("msg", "已支付成功!");
				return re;
			}
		else
			{
				re.setv("ok", true).setv("msg", "支付金额不足！");
				return re;
			}
	}
	
	
	
	/**
	 * 添加产品
	 * @param pro
	 * @param quantity
	 */
	@At("/edit_product")
	public Object editProduct(@Param("id")int id, @Param("count")int count){
		if(count > 0) { // 添加
	        Cnd cnd = Cnd.where("product_id", "=", id);
			Product pro = dao.fetch(Product.class, cnd);
			dao.fetchLinks(pro, "money");
			if(sale.getProducts() == null) {
				sale.setProducts(new ArrayList<Product>());
			}
			for (int i = 0; i < count; i++) {
				sale.getProducts().add(pro);
			}
		} else if(count < 0) { // 删除
			for (int i = sale.getProducts().size() - 1; i >= 0; i++) {
				if(id == sale.getProducts().get(i).getProductId()) {
					sale.getProducts().remove(i);
					break;
				}
			}
		}
		return updateList();
	}
	
	@At("/query")
	public Object queryAll() {
		
        List<Sale> sales = new ArrayList<>();
        
        List<Sale> result = dao.query(Sale.class, null);
        
        Map<Object, Integer> map = new HashMap<>();
        for (Sale model : result) {
			dao.fetchLinks(model, "totalAmount");
			dao.fetchLinks(model, "customerPay");
			dao.fetchLinks(model, "employee");
			dao.fetchLinks(model, "products");
			dao.fetchLinks(model, "isPay");
			System.out.println(model.isPay()+"pay");
			for (Product product : model.getProducts()) {
				dao.fetchLinks(product, "money");
				
				//产品数量
				map.put(model.getOrderId() + "-" + product.getProductId(),
					dao.query(SaleList.class, Cnd
					   .where("orderId", "=", model.getOrderId())
					   .and("productId", "=", product.getProductId())).size());
				
				System.out.println(product.getProductName() + "产品数量：" + dao.query(SaleList.class, Cnd
						   .where("orderId", "=", model.getOrderId())
						   .and("productId", "=", product.getProductId())).size() + "价格：" + dao.fetchLinks(product, "money"));
			}
			
			sales.add(model);
		}
		NutMap re = new NutMap();
        re.setv("ok", true).setv("list", sales);
        re.setv("ok", true).setv("map", map);
        return re;
	}
	
	/**
	 * 计算总额
	 * @param total
	 * @param subtotal
	 * @return
	 */
	public Money getTotal(){
		sale.summary();
		return sale.getTotalAmount();
	}
	
	
	
}
